<?php
/**
 * Created by PhpStorm.
 * User: wolf
 * Date: 2018/8/28
 * Time: 14:25
 */

namespace App\Http\Controllers\Web;


use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Shop;
use App\Tools\Geohash;
use App\Tools\WechatSend;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

// 商品推荐
class RecommendController extends Controller
{
    public function index(){
//        $user_id = 2 ;
//        Redis::set('recommend_user_'.$user_id,'456');
//        $test_msg = Redis::get('recommend_user_'.$user_id);
//        echo $test_msg;
//        $wechatSend = new WechatSend();
//        dd($wechatSend->sendMiniReserveTemplate(166));
//        $user = User::where('id',3)->first();
//        Auth::login($user);
        $order_price = Order::where('id',6)->first(['order_price']);
        $points = round($order_price->order_price);
        return $points;
    }
    public function build(){
        $geohash=new Geohash();
        $shops = Shop::all(['id','latitude','longitude','geo_code']);
        foreach ($shops as $shop){
            $geo_value = $geohash->encode($shop->latitude,$shop->longitude);
            DB::table('shops')->where('id',$shop->id)->update(['geo_code'=>$geo_value]);
        }
        $shopss = Shop::all(['id','latitude','longitude','geo_code']);
        return $shopss;
    }
    public function testGeo(){
        $geohash=new Geohash();
//经纬度转换成Geohash
//获取附近的信息

        $n_latitude  =  23.40391;
        $n_longitude = 113.22026;

        //echo "当前位置为：经度108.7455，纬度34.3608<br/><br/>以下网点离我最近：";

//开始
        $b_time = microtime(true);

//方案A，直接利用数据库存储函数，遍历排序

//方案B geohash求出附近，然后排序

//当前 geohash值
        $n_geohash = $geohash->encode($n_latitude,$n_longitude);

//附近
        $n = 3;
        $like_geohash = substr($n_geohash, 0, $n);
        $res = DB::table('shops')
            ->where('geo_code','like',$like_geohash."%")
            ->get(['id','shop_name','shop_address','longitude','latitude','geo_code']);
        //算出实际距离
        foreach($res as $key=>$val)
        {
            $distance = $this->getDistance($n_latitude,$n_longitude,$val->latitude,$val->longitude);
            $val->distance = $distance;

            //排序列
//            $res[$key] = $distance;
        }
        return $res;
        //$sql = 'select * from retailersinfotable where geohash like "'.$like_geohash.'%"';



//        $query = mysql_query($sql);
//        if(mysql_num_rows($query))
//        {
//            while($row=mysql_fetch_array($query))
//            {
//                $data[] = array (
//                    "latitude" =>$row["Latitude"],
//                    "longitude"=>$row["Longitude"],
//                    "name"
//                    =>$row["RetailersName"],
//                );
//            }
//        }
//

//
//        //距离排序
//        array_multisort($sortdistance,SORT_ASC,$data);
//
//        //结束
//        $e_time = microtime(true);
//
//        echo "（计算耗时：" ;
//        echo $e_time - $b_time;
//        echo "秒）<br/>";
//
////var_dump($data);
//
//        foreach($data as $key=>$val)
//        {
//            echo "</br>";
//            echo $val['distance']. " 米-------".$val['name'];
//        }
    }
    /**
     *  @desc 根据两点间的经纬度计算距离
     *  @param float $latitude 纬度值
     *  @param float $longitude 经度值
     */
    function getDistance($latitude1, $longitude1, $latitude2, $longitude2)
    {
        $earth_radius = 6371000;   //approximate radius of earth in meters

        $dLat = deg2rad($latitude2 - $latitude1);
        $dLon = deg2rad($longitude2 - $longitude1);
        /*
          Using the
          Haversine formula

          http://en.wikipedia.org/wiki/Haversine_formula
          http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe
          验证：百度地图  http://developer.baidu.com/map/jsdemo.htm#a6_1
          calculate the distance
        */
        $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2);
        $c = 2 * asin(sqrt($a));
        $d = $earth_radius * $c;

        return round($d);   //四舍五入
    }
}
